package tech.xs.workflow.bpmn;

import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.xs.workflow.bpmn.constant.BpmnElementConstant;
import tech.xs.workflow.bpmn.element.BpmnBaseElement;
import tech.xs.workflow.bpmn.element.ProcessElement;

public class BpmnElementHelper {

    private final static Logger log = LoggerFactory.getLogger(BpmnElementHelper.class);

    @SneakyThrows
    public static ProcessElement analyze(String fileContent) {
        log.info("导入内容:\n" + fileContent);
        fileContent = removeIntroduction(fileContent);
        Document document = DocumentHelper.parseText(fileContent);
        Element rootElement = document.getRootElement();
        Element processElement = rootElement.element(BpmnElementConstant.PROCESS);
        ProcessElement process = new ProcessElement();
        process.setId(processElement.attributeValue("id"));
        process.setEvents(BpmnEventElementHelper.analyze(processElement));
        process.setSequenceFlows(BpmnSequenceFlowElementHelper.analyze(processElement));
        return process;
    }

    /**
     * 移除xml的前言
     *
     * @param content xml内容
     * @return 移除前言后的内容
     */
    private static String removeIntroduction(String content) {
        if (!content.trim().replaceAll("\uFEFF", "").startsWith("<?xml")) {
            return content;
        }
        return content.substring(content.lastIndexOf("?>") + "?>".length());
    }

    protected static void analyzeBaseNode(Element element, BpmnBaseElement node) {
        node.setId(element.attributeValue("id"));
        node.setName(element.attributeValue("name"));
    }

}
